package com.beiding.dao.impl;

import com.beiding.dao.KeyValueDao;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Repository
class KeyValueDaoImpl implements KeyValueDao {


    private ValueOperations<String, Object> ops;

    private RedisTemplate<String, Object> redisTemplate;

    KeyValueDaoImpl(RedisConnectionFactory factory){

        redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());

        redisTemplate.afterPropertiesSet();

        ops = redisTemplate.opsForValue();

    }

    public Object get(String key) {

        return ops.get(key);
    }

    public void put(String key, Serializable value, long validSeconds) {
        ops.set(key, value, validSeconds, TimeUnit.SECONDS);
    }


    public void remove(String key) {
        redisTemplate.delete(key);
    }

}
